ActiveAdmin.register Curriculum::Schedule do
  actions :index, :show, :destroy

  filter :coach_name, as: :string, label: '教练'
  filter :schedulable_type
  filter :class_start_time
  before_action only: :index do
    if params[:q].present?
      keys = %w"coach_name_contains coach_name_equals coach_name_starts_with coach_name_ends_with"
      keys.each do |key|
        if params[:q][key].present?
          ids = Coach.ransack("#{key.gsub("coach_", '')}": params[:q][key]).result.pluck(:id)
          params[:q].reject! {|k, v| k.include?(key)}
          params[:q].merge!(coach_id_in: ids)
          break
        end
      end
    end
  end

  index do
    selectable_column
    column :schedulable_id
    column :schedulable_type
    column '教练' do |schedule|
      "#{schedule.coach.try(:name)}(#{schedule.coach_id})"
    end
    column :class_start_time
    column :class_end_time
    actions
  end

  show do
    attributes_table do
      row :coach
      row :schedulable_type
      row :schedulable_id
      row '课程信息' do |schedule|
        attributes_table_for schedule.timetable do
          row :id
          row '门店' do |t|
            "#{t.store.name} [#{t.store.id}]"
          end
          row '教室' do |t|
            "#{t.classroom.name} [#{t.classroom.id}]"
          end
          row '教练' do |t|
            "#{t.coach.name} [#{t.coach.id}]"
          end
          row :class_start_time
          row :class_end_time
          row :status_i18n
        end
      end
      row :class_start_time
      row :class_end_time
      row :created_at
    end
  end

  controller do
    def scoped_collection
      Curriculum::Schedule.includes(:coach)
    end

    def destroy
      begin
        destroy!
      rescue Exception => exp
        redirect_to "/admin/curriculum_schedules", flash: {error: exp.message}
      end
    end
  end
end
